package com.agileai.bpm.controller.instance;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.agileai.bpm.bizmoduler.define.WfProcessManage;
import com.agileai.bpm.service.running.ProcessHandle;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.common.TemplateHelper;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

public class WfProcessHistoryListHandler extends BaseHandler{
	public WfProcessHistoryListHandler(){
		super();
	}
	public ViewRenderer prepareDisplay(DataParam param){
		mergeParam(param);
		initParameters(param);
		this.setAttributes(param);
		
		boolean embed = param.getBoolean("embed",false);
		String userId = param.get("userId");
		if (embed){
			User user = (User)this.getUser();
			userId = user.getUserId();
		}
		if (!StringUtil.isNullOrEmpty(userId)){
			param.put("seqId", userId,"type",ProcessHandle.UserSeqType.USER_ID);
			List<DataRow> rsList = getService().queryDidWorkList(param);
			List<DataRow> recordsList = new ArrayList<DataRow>();
			for (int i = 0,length = rsList.size(); i < length; i++) {
				DataRow row = rsList.get(i);
				String detailUrl = row.getString("WFP_DETAIL_URL");
				TemplateHelper templateHelper = new TemplateHelper();
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				HashMap<String, String> modelMap = new HashMap<String, String>();
				modelMap.put("__bizRecordId__",row.getString("WFHP_BUSINESS_ID"));
				templateHelper.generate(detailUrl, modelMap, outputStream);
				detailUrl = outputStream.toString();
				row.put("WFP_DETAIL_URL",detailUrl);
				recordsList.add(row);
			}
			this.setRsList(recordsList);
		}
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
	
	@PageAction
	public ViewRenderer query(DataParam param){
		return prepareDisplay(param);
	}
	
	protected void processPageAttributes(DataParam param) {
		
	}
	protected void initParameters(DataParam param) {
		 initParamItem(param, "sdate", 
	        		DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, DateUtil.getDateAdd(new Date(), DateUtil.DAY, -40)));
	     initParamItem(param, "edate", 
	        		DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, new Date()));
	}
	
	protected WfProcessManage getService() {
		return (WfProcessManage)this.lookupService(WfProcessManage.class);
	}
}	
